package com.hxd.common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class ImageMd5Util {
	
	public static String getFileMD5(File file) {
		if (!file.isFile()) {
			return null;
		}
		// 创建MessageDigest对象，添加MD5处理
		MessageDigest digest = null;
		FileInputStream in = null;
		byte buffer[] = new byte[1024];
		int len;
		try {
			digest = MessageDigest.getInstance("MD5");
			// 读取图片
			in = new FileInputStream(file);
			while ((len = in.read(buffer, 0, 1024)) != -1) {
				digest.update(buffer, 0, len);
			}
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

		BigInteger bigInt = new BigInteger(1, digest.digest());
		System.out.println(bigInt);
		// 返回16进制表示形式
		return bigInt.toString(16);
	}
	
	public static String getFileMD5(InputStream in) {
		// 创建MessageDigest对象，添加MD5处理
		MessageDigest digest = null;
		byte buffer[] = new byte[1024];
		int len;
		try {
			digest = MessageDigest.getInstance("MD5");
			while ((len = in.read(buffer, 0, 1024)) != -1) {
				digest.update(buffer, 0, len);
			}
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

		BigInteger bigInt = new BigInteger(1, digest.digest());
		System.out.println(bigInt);
		// 返回16进制表示形式
		return bigInt.toString(16);
	}
	
	
	public static String getUrlFileMD5(String fileUrl) throws Exception{
		fileUrl = urlCode(fileUrl);
		System.out.println("encode后 " +  fileUrl);
        URL url;
        HttpURLConnection urlConnection = null;
        InputStream inputStream = null;
		url = new URL(fileUrl);
        urlConnection = ( HttpURLConnection ) url.openConnection();
        urlConnection.connect();
        inputStream = urlConnection.getInputStream();
        String fileMD5 = getFileMD5(inputStream);
        System.out.println(fileUrl + " 的MD5值是：" + fileMD5);
        return fileMD5;
	}
	
	public static String urlCode(String filepath) throws UnsupportedEncodingException {
		String fileUrl = filepath ;
//		filepath.substring(0,filepath.lastIndexOf("."));
	    String str[] = fileUrl.split("/");
	    for(int i = 0;i<str.length;i++){
	       Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
	       Matcher m = p.matcher(str[i]);
	       if (m.find()) {
	          filepath = filepath.replaceFirst(str[i], URLEncoder.encode(str[i],"UTF-8"));
	       }
	    }
	    return filepath;
	}

	public static void main(String[] args) throws Exception {
		String imgUrl ="http://imgcdn.huixdou.com/2019/031/25/5b73da0412ff474f8730f8643fd14caa.png";
		getUrlFileMD5(imgUrl);
	}

}
